# main_strategy.py
from qmt import *
from strategy_instance import StrategyInstance
from flask_api import start_flask_api, init_flask_api
import threading
import time
import main2

# 全局变量
strategy_pool = {}  # Dict[str, StrategyInstance]
subscribe_quote = {}
ACCOUNT_ID = None

def on_init(context):
    global ACCOUNT_ID
    ACCOUNT_ID = context.accounts[0].account_id
    print(f"账户初始化完成: {ACCOUNT_ID}")

    # 初始化 Flask API（在子线程）
    main2.init_flask_api(strategy_pool, ACCOUNT_ID, subscribe_quote)
    flask_thread = threading.Thread(target=start_flask_api, args=(5000,), daemon=True)
    flask_thread.start()
    print("Flask 控制接口已启动: http://localhost:5000")

    # 可选：加载初始股票（从配置文件或 Redis）
    initial_symbols = ['600519.SH']  # 如需预加载，填入 ['600519.SH', ...]
    for sym in initial_symbols:
        strategy_pool[sym] = StrategyInstance(sym, {
            "ma_window": 20,
            "vol_multiplier": 1.5,
            "order_volume": 100,
            "cool_down": 5
        })
    
    if initial_symbols:
        subscribe_quote(initial_symbols)
        print(f"已订阅初始股票: {initial_symbols}")



def on_tick(context, ticks):
    """QMT tick 回调（主线程）"""
    for tick in ticks:
        stock_code = tick.stock_code
        if stock_code in strategy_pool:
            try:
                strategy_pool[stock_code].on_tick(tick, ACCOUNT_ID)
            except Exception as e:
                print(f"[ERROR] {stock_code} on_tick 异常: {e}")



def on_order_status(context, order):
    """QMT 成交回报回调（主线程）"""
    for instance in strategy_pool.values():
        try:
            instance.on_order_status(order)
        except Exception as e:
            print(f"[ERROR] {instance.stock_code} on_order_status 异常: {e}")

# ======================
# 以下为辅助函数（可选）
# ======================
def on_bar(context, bars):
    pass

def on_finish(context):
    print("策略结束")